package top.yongyan0624.controller;

import com.aliyun.oss.internal.OSSUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.yongyan0624.Utils.OSSUtil;
import top.yongyan0624.common.dto.SysUserDto;
import top.yongyan0624.common.lang.CodeMsg;
import top.yongyan0624.common.lang.Const;
import top.yongyan0624.common.lang.ResultVO;
import top.yongyan0624.entity.MyList;
import top.yongyan0624.entity.SysRole;
import top.yongyan0624.entity.SysUser;
import top.yongyan0624.entity.SysUserRole;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 讽惘
 * @since 2021-05-13
 */
@RestController
public class SysUserController extends BaseController {

    @PreAuthorize("hasAnyRole('admin','superAdmin')")
    @GetMapping("/admin/queryUser")
    public ResultVO queryUser(@RequestParam(required = false) String username) {
        Page<SysUser> userPage = sysUserService.queryList(getPage(), username);

        return ResultVO.success("查询成功", userPage);
    }

    @PreAuthorize("hasAnyRole('admin','superAdmin')")
    @GetMapping("/admin/queryUserByRoleName")
    public ResultVO queryUserByRoleName(@RequestParam String roleName) {
        Page<SysUser> userPage = sysUserService.queryUserByRoleName(getPage(), roleName);

        return ResultVO.success(userPage);
    }

    @PostMapping("/users/register")
    public ResultVO<SysUser> register(@RequestParam String username, @RequestParam String password) {
        if (username == null || password == null) {
            return ResultVO.error(new CodeMsg("用户名或密码不能为空！"));
        }
        if (sysUserService.count(new QueryWrapper<SysUser>().eq("username", username)) > 0) {
            return ResultVO.error(new CodeMsg("注册失败！用户已经存在！"));
        }

        SysUser user = sysUserService.register(username, password);

        if (user != null) {
            return ResultVO.success("注册成功", user);
        }
        return ResultVO.error(new CodeMsg(500, "对不起！出错了，注册失败！"));
    }

    @PreAuthorize("hasRole('superAdmin')")
    @PostMapping("/admin/addUser")
    public ResultVO<SysUser> addUser(@RequestBody SysUser sysUser) {
        if (sysUser.getUsername() == null) {
            return ResultVO.error(new CodeMsg("用户名不能为空！"));
        }

        if (sysUserService.count(new QueryWrapper<SysUser>().eq("username", sysUser.getUsername())) > 0) {
            return ResultVO.error(new CodeMsg("新增失败！用户已经存在！"));
        }

        if (sysUserService.addUser(sysUser)) {
            return ResultVO.success("新增成功", sysUser);
        }
        return ResultVO.error(new CodeMsg(500, "对不起！出错了，新增失败！"));
    }

    @PostMapping("/users/Modification")
    public ResultVO Modification(@RequestBody SysUser sysUser) {
        sysUser.setUsername(null);
        sysUser.setPassword(null);
        //根据id修改用户信息
        if (sysUserService.updateById(sysUser)) {
            return ResultVO.success("修改成功！", sysUser);
        }

        return ResultVO.error(new CodeMsg("修改出错啦！"));
    }

    @PostMapping("/users/ModificationPassword")
    public ResultVO ModificationPassword(@RequestBody SysUser sysUser) {
        SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().eq("id", sysUser.getId()));
        if (user != null) {
            user.setPassword(passwordEncoder.encode(sysUser.getPassword()));
            //根据id修改用户信息
            if (sysUserService.updateById(user)) {
                return ResultVO.success("修改成功！");
            }
        }

        return ResultVO.error(new CodeMsg("对不起！用户不存在，修改失败！"));
    }

    @PostMapping("/users/modifyAvatar/{id}")
    public ResultVO modifyAvatar(@PathVariable("id") Long id, MultipartFile avatar) {
        SysUser user = new SysUser();
        user.setId(id);
        if (avatar.isEmpty()) {
            return ResultVO.error(new CodeMsg(404,"头像路径为空"));
        }
        //存储文件，同时获取图片URL
        String url = OSSUtil.getImgUrl(avatar);

        //设置用户头像URL
        user.setAvatar(url);
        sysUserService.updateById(user);
        return ResultVO.success(user);
    }

    @PreAuthorize("hasRole('superAdmin')")
    @Transactional
    @PostMapping("/admin/updateUserModification")
    public ResultVO updateUserModification(@RequestBody SysUserDto userDto) {
        SysUser sysUser = userDto.getSysUser();
        Long[] roleIds = userDto.getRoleIds();

        sysUser.setUsername(null);
        sysUser.setPassword(null);

        if (sysUserService.updateById(sysUser) && sysUserService.rolePerm(sysUser.getId(), roleIds)) {
            sysUserService.setRoles(sysUser);
            return ResultVO.success("修改成功！", sysUser);
        }

        return ResultVO.error(new CodeMsg("修改出错啦！"));
    }

    @PreAuthorize("hasRole('superAdmin')")
    @Transactional
    @PostMapping("/admin/updateUserModificationPassword")
    public ResultVO updateUserModificationPassword(@RequestBody SysUser sysUser) {

        SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().eq("id", sysUser.getId()));
        if (user != null) {
            user.setPassword(passwordEncoder.encode(sysUser.getPassword()));

            if (sysUserService.updateById(user)) {
                return ResultVO.success("修改成功！");
            }
        }

        return ResultVO.error(new CodeMsg("对不起！用户不存在，修改失败！"));
    }

    @GetMapping("/admin/user/repass/{id}")
    @PreAuthorize("hasRole('superAdmin')")
    public ResultVO repass(@PathVariable Long id) {

        SysUser sysUser = sysUserService.getById(id);

        sysUser.setPassword(passwordEncoder.encode(Const.DEFULT_PASSWORD));

        sysUserService.updateById(sysUser);
        return ResultVO.success("密码重置成功：888888");
    }

    @PreAuthorize("hasRole('superAdmin')")
    @Transactional
    @RequestMapping("/admin/delUser/{id}")
    public ResultVO delUser(@PathVariable Long id) {
        boolean ok = sysUserService.removeById(id);

        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", id));
        //清除权限缓存
        sysUserService.clearUserAuthorityInfo(id);
        if (ok) {
            return ResultVO.success("删除成功！");
        }

        return ResultVO.error(new CodeMsg("对不起！不存在这个用户，删除失败！"));
    }

    @PreAuthorize("hasRole('superAdmin')")
    @Transactional
    @RequestMapping("/admin/delAllUser")
    public ResultVO delAllUser(@RequestBody MyList<Long> myList) {
        List<Long> ids = myList.getList();
        for (Long id : ids) {
            if (delUser(id).getCode() == 400) {
                return ResultVO.error(new CodeMsg("对不起！不存在这个用户:" + id + "，删除失败！"));
            }
        }
        return ResultVO.success("删除成功！");
    }

    @PreAuthorize("hasAnyRole('admin','superAdmin')")
    @RequestMapping("/admin/countUser")
    public ResultVO countUser() {
        return ResultVO.success("查询成功", sysUserService.count());
    }
}
